<template>
  <div class="myDiv">
    <div class="header">
      <el-button @click="gotoTargetPage" class="back">返回</el-button>
      <UserAcatar @transfer="change" />
    </div>

    <div
      v-loading="loading"
      element-loading-text="拼命加载中"
      class="board-column"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item
          name="单选题"
          v-if="list.singleChoiceQuestions && list.singleChoiceQuestions.length"
        >
          <template slot="title">
            <span style="font-size: 23px; font-weight: 700"
              >单项选择题(共{{ list.singleChoiceQuestions.length }}题, 每题{{
                list.singleChoiceQuestions[0].proportion
              }}分, 共{{
                list.singleChoiceQuestions.length *
                list.singleChoiceQuestions[0].proportion
              }}分)</span
            >
          </template>
          <div
            v-for="(element, questionIndex) in list.singleChoiceQuestions"
            v-click-outside="{ handler: hideButtons, element: element }"
            :key="element.id"
            class="board-item"
          >
            <!-- 单选题模板 -->
            <div
              v-if="element.questionType == '单选题'"
              class="item"
              :class="{ active: element.showAdd }"
              @click="element.showAdd = true"
            >
              <div class="question" style="margin-bottom: 20px">
                <div style="">
                  <span style="color: red; font-size: 20px; margin-right: "
                    >*</span
                  ><span class="questionNumber">{{ questionIndex + 1 }}.</span>
                  <span
                    class="questionContent"
                    v-show="!element.editing"
                    @click="clickQuestion(element, questionIndex)"
                    >{{ element.question }}</span
                  >
                </div>
                <div>
                  <span
                    class="score"
                    style="color: #ccc"
                    v-show="!element.editScore"
                    >{{ element.proportion }} 分</span
                  >
                </div>
              </div>
              <div>
                <el-radio-group v-model="singleAnswer[questionIndex]">
                  <div
                    v-for="(optionElement, optionsIndex) in element.optionsList"
                    :key="optionElement.id"
                    @mouseenter="optionElement.isHovered = false"
                    @mouseleave="optionElement.isHovered = true"
                    class="board-item"
                    style="diplay: flex; justify-content: space-between"
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        padding-left: 50px;
                        margin-bottom: 20px;
                      "
                    >
                      <el-radio
                        style="margin-left: 8px"
                        :label="optionElement.content"
                      >
                        {{ optionsItem[optionsIndex] }}.
                        {{ optionElement.content }}
                      </el-radio>
                    </div>
                  </div>
                </el-radio-group>
              </div>
              <div
                class="getScore"
                v-if="typeof element.score === 'number'"
              ></div>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item
          name="多选题"
          v-if="
            list.multipleChoiceQuestions && list.multipleChoiceQuestions.length
          "
        >
          <template slot="title">
            <span style="font-size: 23px; font-weight: 700"
              >多项选择题(共{{ list.multipleChoiceQuestions.length }}题, 每题{{
                list.multipleChoiceQuestions[0].proportion
              }}分, 共{{
                list.multipleChoiceQuestions.length *
                list.multipleChoiceQuestions[0].proportion
              }}分)</span
            >
          </template>
          <!-- 多选题模板 -->
          <div
            v-for="(element, questionIndex) in list.multipleChoiceQuestions"
            :key="element.id"
            class="board-item"
          >
            <div
              v-if="element.questionType == '多选题'"
              class="item"
              :class="{ active: element.showAdd }"
              @click="element.showAdd = true"
            >
              <div class="question" style="margin-bottom: 20px">
                <div style="">
                  <span style="color: red; font-size: 20px; margin-right: "
                    >*</span
                  ><span class="questionNumber">{{ questionIndex + 1 }}.</span>
                  <span
                    class="questionContent"
                    v-show="!element.editing"
                    @click="clickQuestion(element, questionIndex)"
                    >{{ element.question }}</span
                  >
                </div>
                <div>
                  <span
                    class="score"
                    style="color: #ccc"
                    v-show="!element.editScore"
                    @click="changeScore(element, questionIndex)"
                    >{{ element.proportion }} 分</span
                  >
                </div>
              </div>
              <div>
                <el-checkbox-group v-model="multipleAnswer[questionIndex]">
                  <div
                    v-for="(optionElement, optionsIndex) in element.optionsList"
                    :key="optionElement.id"
                    @mouseenter="optionElement.isHovered = false"
                    @mouseleave="optionElement.isHovered = true"
                    class="board-item"
                    style="diplay: flex; justify-content: space-between"
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        padding-left: 50px;
                        margin-bottom: 20px;
                      "
                    >
                      <el-checkbox
                        :label="optionElement.content"
                        @change="changeCheck(val)"
                        style="margin-left: 8px"
                      >
                        {{ optionsItem[optionsIndex] }}.
                        {{ optionElement.content }}
                      </el-checkbox>
                    </div>
                  </div>
                </el-checkbox-group>
              </div>
              <div
                class="getScore"
                :class="{
                  correct: element.proportion == element.score,
                  mistake: element.score == 0,
                  warning:
                    element.score != 0 && element.score < element.proportion,
                }"
                v-if="element.score"
              ></div>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item name="简答题" v-if="list.shortAnswerQuestions.length">
          <template slot="title">
            <span style="font-size: 23px; font-weight: 700"
              >简答题(共{{ list.shortAnswerQuestions.length }}题, 每题{{
                list.shortAnswerQuestions[0].proportion
              }}分, 共{{
                list.shortAnswerQuestions.length *
                list.shortAnswerQuestions[0].proportion
              }}分)</span
            >
          </template>
          <div
            v-for="(element, questionIndex) in list.shortAnswerQuestions"
            :key="element.id"
            class="board-item"
          >
            <!-- 简答题模板 -->
            <div
              v-if="element.questionType == '简答题'"
              class="item"
              :class="{ active: element.showAdd }"
              v-click-outside="{ handler: hideButtons, element: element }"
              @click="element.showAdd = true"
            >
              <div class="question" style="margin-bottom: 20px">
                <div>
                  <span style="color: red; font-size: 20px; margin-right: "
                    >*</span
                  ><span class="questionNumber">{{ questionIndex + 1 }}.</span>
                  <span
                    class="questionContent"
                    v-show="!element.editing"
                    @click="clickQuestion(element, questionIndex)"
                    >{{ element.question }}</span
                  >
                </div>
                <div>
                  <span
                    class="score"
                    style="color: #ccc"
                    v-show="!element.editScore"
                    @click="changeScore(element, questionIndex)"
                    >{{ element.proportion }} 分</span
                  >
                </div>
              </div>
              <el-input
                style="width: 100%"
                ref="questionInput"
                type="textarea"
                min-row="3"
                :autosize="true"
                v-model="shortAnswer[questionIndex]"
              />
              <!-- <QuillEditor class="getcontent" v-bind:choice="answer[questionIndex]" /> -->
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="submitContainer">
      <el-button type="success" @click="submit" v-if="handle !== 'edit'"
        >提交作业</el-button
      >
      <el-button type="success" @click="submit" v-if="handle === 'edit'"
        >修改作业</el-button
      >
    </div>
  </div>

  <!-- <QuillEditor class="getcontent" v-bind:choice="choice" /> -->
</template>

<script>
import UserAcatar from "@/components/UserAcatar.vue"; //引入组件
import QuillEditor from "@/components/submitjob/TextEditing.vue";
import store from "@/store/index";
export default {
  name: "SubmitWork",
  components: {
    UserAcatar,
    QuillEditor,
  },
  data() {
    return {
      testobj: {},
      userInfo: "",
      testid: "",
      choice: "提交任务",
      questionList: [],
      selectAnswer: [],
      checkboxValues: [],
      radio: "",
      singleAnswer: [],
      multipleAnswer: [],
      shortAnswer: [],
      loading: false,
      handle: "",
      assignmentInfo: {},
      list: {},
      optionsItem: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      activeNames: ['单选题','多选题', '简答题'],
    };
  },
  methods: {
    changeCheck(val) {
      console.log(val);
      console.log(this.multipleAnswer);
    },
    gotoTargetPage() {
      this.$router.go(-1);
    },
    // 生成随机数
    generateUniqueRandomNumber() {
      let timestamp = new Date().getTime(); // 获取当前时间戳
      let randomNumber = Math.floor(Math.random() * 1000); // 生成0到999之间的随机数
      let uniqueRandomNumber = timestamp.toString() + randomNumber.toString(); // 将时间戳和随机数拼接起来
      return parseInt(uniqueRandomNumber);
    },
    // 将头像组件中的路由再传递给homeview
    change(msg) {
      this.$emit("transfer", msg);
    },
    // 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
    formTime(time) {
      let newtime = new Date(time);
      console.log(new Date(time), "要进行转换的时间");
      const year = newtime.getFullYear();
      const month = String(newtime.getMonth() + 1).padStart(2, "0");
      const day = String(newtime.getDate()).padStart(2, "0");
      const hours = String(newtime.getHours()).padStart(2, "0");
      const minutes = String(newtime.getMinutes()).padStart(2, "0");
      const seconds = String(newtime.getSeconds()).padStart(2, "0");

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate;
    },

    async submit() {
      let obj = {};
      obj.assignmentId = this.$route.query.workid;
      obj.student_id = this.userInfo.student_id;
      obj.submit_time = this.formTime(new Date());
      obj.student_assignment_id = this.$route.query.student_assignment_id;
      console.log(obj.student_assignment_id, "sadas");
      let singleArr = [];
      let multipleArr = [];
      let shortArr = [];
      for (let i = 0; i < this.list.singleChoiceQuestions.length; i++) {
        let obj = {};
        obj.question_type = this.list.singleChoiceQuestions[i].questionType;
        obj.answer = this.singleAnswer[i];
        obj.correct_answer = this.list.singleChoiceQuestions[i].answer;
        obj.question_id = this.list.singleChoiceQuestions[i].question_id;
        singleArr.push(obj);
      }

      for (let i = 0; i < this.list.multipleChoiceQuestions.length; i++) {
        let obj = {};
        obj.question_type = this.list.multipleChoiceQuestions[i].questionType;
        obj.answer = this.multipleAnswer[i];
        obj.correct_answer = this.list.multipleChoiceQuestions[i].answer;
        obj.question_id = this.list.multipleChoiceQuestions[i].question_id;
        multipleArr.push(obj);
      }

      for (let i = 0; i < this.list.shortAnswerQuestions.length; i++) {
        let obj = {};
        obj.question_type = this.list.shortAnswerQuestions[i].questionType;
        console.log(this.shortAnswer[i]);
        obj.answer = this.shortAnswer[i];
        obj.correct_answer = this.list.shortAnswerQuestions[i].answer;
        obj.question_id = this.list.shortAnswerQuestions[i].question_id;
        shortArr.push(obj);
      }

      obj.singleArr = singleArr;
      obj.multipleArr = multipleArr;
      obj.shortArr = shortArr;
      obj.handle = this.handle;
      console.log(obj);

      let res = await this.$axios.post("/submitjob/submitJob", obj);
      console.log(res);
      if (res.code == 200) {
        if (this.handle === "edit") {
          this.$notify({
            title: "成功",
            message: "作业修改成功",
            type: "success",
          });
        } else {
          this.$notify({
            title: "成功",
            message: "作业提交成功",
            type: "success",
          });
        }
        this.$router.push({
          path: "submitjob",
          query: { nowStatus: "published" },
        });
      }
    },
    async getAssignmentInfo() {
      this.loading = true;
      console.log(this.$route.query.student_assignment_id)
      let res = await this.$axios.post("/submitjob/getAssignmentInfo", {
        assignmentId: this.$route.query.workid,
        handle: this.$route.query.handle,
        student_assignment_id: this.$route.query.student_assignment_id
      });
      console.log(res);
      this.loading = false;
      this.assignmentInfo = res.assignmentInfo;
      this.list = {...res.assignmentInfo.questions};
      console.log(this.list);
      this.list.singleChoiceQuestions = this.list.singleChoiceQuestions.map(
        (item) => {
          let obj = {};
          console.log(obj.student_answer);
          console.log(item, "item");
          obj.question_id = item.question_id;
          obj.question = item.choice_question;
          console.log(obj);
          obj.id = this.generateUniqueRandomNumber();
          if(item.student_answer) {
            obj.student_answer = JSON.parse(item.student_answer);
          }
          obj.editing = false;
          obj.showAdd = false;
          obj.answer = JSON.parse(item.correct_answer);
          obj.questionType = item.question_type;
          obj.proportion = item.proportion;
          obj.optionsList = JSON.parse(item.options_list);
          return obj;
        }
      );
      this.list.shortAnswerQuestions = this.list.shortAnswerQuestions.map(
        (item) => {
          let obj = {};
          console.log(item, "item");
          obj.question_id = item.question_id;
          obj.question = item.essayQuestion;
          obj.id = this.generateUniqueRandomNumber();
          if(item.student_answer) {
            obj.student_answer = item.student_answer
          }
          obj.editing = false;
          obj.showAdd = false;
          obj.answer = item.correct_answer;
          obj.questionType = item.question_type;
          obj.proportion = item.proportion;
          return obj;
        }
      );
      this.list.multipleChoiceQuestions = this.list.multipleChoiceQuestions.map(
        (item) => {
          let obj = {};
          console.log(item, "item");
          obj.question_id = item.question_id;
          obj.question = item.choice_question;
          if(item.student_answer) {
            obj.student_answer = JSON.parse(item.student_answer);
          }
          obj.id = this.generateUniqueRandomNumber();
          obj.editing = false;
          obj.showAdd = false;
          obj.answer = JSON.parse(item.correct_answer);
          obj.questionType = item.question_type;
          obj.proportion = item.proportion;
          obj.optionsList = JSON.parse(item.options_list);
          return obj;
        }
      );
      console.log(this.list);
    },
    hideButtons(element) {
      element.showAdd = false;
    },
    gotoTargetPage() {
      this.$router.push({ path: "correct" });
    },
    change(msg) {
      this.$emit("transfer", msg);
    },
    editScore() {
      this.dialogVisible = true;
      this.correctForm.score = this.work.score;
      this.correctForm.comment = this.work.comment;
    },
  },
  async mounted() {
    console.log(this.$route.query);
    this.userInfo = JSON.parse(JSON.stringify(store.state.user_info));
    this.testobj = this.$route.query;
    console.log(this.testobj.testid);
    this.testid = this.testobj.testid;
    this.handle = this.$route.query.handle;
    await this.getAssignmentInfo();

    this.singleAnswer = this.list.singleChoiceQuestions.map((item) => {
      return "";
    });
    this.multipleAnswer = this.list.multipleChoiceQuestions.map((item) => {
      return [];
    });
    this.shortAnswer = this.list.shortAnswerQuestions.map((item) => {
      return "";
    });

    if(this.$route.query.handle === 'edit') {
      console.log(this.list);
      this.list.singleChoiceQuestions.forEach((element, index) => {
        this.singleAnswer[index] = element.student_answer;
      });
      this.list.multipleChoiceQuestions.forEach((element, index) => {
        this.multipleAnswer[index] = element.student_answer;
      });
      this.list.shortAnswerQuestions.forEach((element, index) => {
        if(element.student_answer) {
          this.shortAnswer[index] = element.student_answer;
        } else {
          this.shortAnswer[index] = ''
        }
        console.log(element.student_answer);
      });
    }
    console.log(this.multipleAnswer);
  },
  created() {},
  // 自定义指令，判断点击位置是否在盒子内部
  directives: {
    clickOutside: {
      bind(el, binding, vnode) {
        el.clickOutsideEvent = function (event) {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value.handler(binding.value.element);
          }
        };
        document.body.addEventListener("mousedown", el.clickOutsideEvent);
      },
      unbind(el) {
        document.body.removeEventListener("mousedown", el.clickOutsideEvent);
      },
    },
  },
};
</script>
<style lang="less" scoped>
.submitContainer {
  // width: 80%;
  // margin: auto;
  display: flex;
  justify-content: center;
  margin-bottom: 50px;
  margin-top: 30px;
}

// .second {
//   display: flex;
//   margin-top: 25px;
//   flex-direction: column;
// }

// .quitbtn {
//   margin-top: 10px;
//   width: 80px;
//   height: 40px;
//   border-radius: 35%;
//   margin-left: 50px;
//   background: linear-gradient(360deg,
//       rgba(248, 249, 253, 0.8),
//       rgba(7, 180, 123, 0.8),
//       rgba(6, 216, 24, 0),
//       rgba(69, 224, 7, 0));
// }

// .font {
//   margin-left: 50px;
//   font-family: "思源黑体";
//   font-weight: bolder;
// }

.myDiv {
  display: flex;
  flex-direction: column;
}

// .first {
//   display: flex;
//   flex-direction: column;
// }

// .content {
//   width: 1000px;
//   height: 150px;
//   margin-top: 20px;
//   margin-left: 50px;
//   box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
// }

.header {
  width: 100%;
  height: 80px;
  border-bottom: 2px solid #bbb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

// .getcontent {
//   margin-top: 10px;
//   margin-left: 50px;
//   width: 1000px;
// }

.item {
  display: flex;
  background: white;
  box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.1),
    -1px 1px 3px 0px rgba(0, 0, 0, 0.1), -3px 5px 6px 0px rgba(0, 0, 0, 0.09),
    -8px 10px 8px 0px rgba(0, 0, 0, 0.05),
    -13px 18px 9px 0px rgba(0, 0, 0, 0.01), -21px 28px 10px 0px rgba(0, 0, 0, 0);
  padding: 30px 50px;
  width: 80%;
  margin: 20px auto;
  flex-direction: column;
  border: 1px solid transparent;
  transition: border-color 0.3s;
  border-radius: 3px;
}

.active {
  border: 2px #409eff solid;
}

.questionContent {
  padding: 5px;
  display: inline-block;
  width: 300px;
  // display: block;
}

.question {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}

.question input {
  outline: none;
  border: none;
  padding: 5px;
  width: 300px;
  background: #f9f9fc;

  white-space: pre-wrap;
}

.questionNumber {
  margin-right: 30px;
}

.container {
  width: 80%;
  margin: auto;
  font-size: 20px;
}

.board-column {
  // max-width: 80%;
  min-height: 100px;
  margin: auto;
  width: 80%;
  height: auto;
  overflow: hidden;
  // background: #f6f7f9;
  border-radius: 3px;

  // .board-column-header {
  //   height: 50px;
  //   line-height: 50px;
  //   overflow: hidden;
  //   padding: 0 20px;
  //   text-align: center;
  //   background: #e6a23c;
  //   color: #fff;
  //   border-radius: 3px 3px 0 0;
  // }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 10px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: auto;
      margin: 5px 0;
      background-color: #fff;
      text-align: left;
      // line-height: 54px;
      padding: 30px 30px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
      display: flex;
    }
  }
}
</style>